package com.dr.dac.knowledgebase.client;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.dr.dac.knowledgebase.KBAidlInterface;


public class MainActivity extends AppCompatActivity {
    private KBAidlInterface server;
    private Button btn1,showBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = (Button) findViewById(R.id.btn1);
        showBtn = (Button) findViewById(R.id.show_view_btn);

        attemptToBindService();

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toActivity();
            }
        });

        showBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    server.show("JS002");

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 跳转Activity
     */
    private void toActivity(){
        ComponentName componetName =
                new ComponentName("com.dr.dac.knowledgebase",
                        "com.dr.dac.knowledgebase.ui.activity.MainActivity");   // 这个参数是要启动的Activity （主activity）
        try {
            Intent intent = new Intent();
            intent.setComponent(componetName);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(),"没有找到应用程序！！！", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 尝试与服务端建立连接
     */
    private void attemptToBindService() {
        Intent intent = new Intent();
        intent.setAction("com.dr.dac.knowledgebase.ui.service.AppServer");
        intent.setPackage("com.dr.dac.knowledgebase");
        bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection myConnection = new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            server = KBAidlInterface.Stub.asInterface(service);
            Log.e("====","myConnection");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Toast.makeText(MainActivity.this,"onServiceDisconnected====",Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(myConnection);
    }
}
